package com.ruoyi.web.controller.system;

import com.baomidou.mybatisplus.core.plugins.IgnoreStrategy;
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.TenantConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.sign.RsaUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author fengcheng
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RuoYiConfig ruoYiConfig;

    @Autowired
    private TenantConfig tenantConfig;

    @Autowired
    private ISysConfigService configService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) throws Exception {
        if(Boolean.parseBoolean(configService.selectConfigByKey("sys_public_demonstrate"))) {
            if(!(Constants.ADMIN.equals(loginBody.getUsername()) && tenantConfig.getDefaultTenantId().equals(loginBody.getTenantId()))){
                if (!ruoYiConfig.getPublicCode().equals(loginBody.getPublicCode())) {
                    return AjaxResult.error("公众号code错误，请关注ruoyi-wvp公众号获取正确的公众号code");
                }
            }
        }

        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(),
                RsaUtils.decryptByPrivateKey(loginBody.getPassword()), loginBody.getTenantId(), loginBody.getCode(), loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions)) {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        InterceptorIgnoreHelper.handle(IgnoreStrategy.builder().tenantLine(true).build());
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        InterceptorIgnoreHelper.clearIgnoreStrategy();
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 切换租户
     *
     * @param tenantId 租户ID
     * @return
     */
    @PostMapping("/switchTenants/{tenantId}")
    public AjaxResult switchTenants(@PathVariable String tenantId) {
        // 创建一个AjaxResult对象，并设置其状态为成功
        AjaxResult ajax = AjaxResult.success();
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();

        // 调用tokenService的delLoginUser方法，删除当前登录用户的token
        tokenService.delLoginUser(loginUser.getTenantId(), loginUser.getToken());

        // 设置当前登录用户的tenantId为传入的tenantId
        loginUser.setTenantId(tenantId);
        // 调用tokenService的createToken方法，创建新的token
        String token = tokenService.createToken(loginUser);
        // 将新的token放入ajax对象中
        ajax.put(Constants.TOKEN, token);
        return ajax;

    }
}
